package com.example.myapplication;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etInput;
    private String currentInput = "";
    private boolean clearFlag = false;

    // 通知相关变量
    private NotificationManager notificationManager;
    private static final String CHANNEL_ID = "calculator_channel";
    private static final int NOTIFICATION_ID = 1;
    private static final int PERMISSION_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        initializeViews();

        // 初始化通知管理器
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 创建通知渠道
        createNotificationChannel();

        // 检查并请求通知权限
        checkNotificationPermission();
    }

    private void initializeViews() {
        etInput = findViewById(R.id.et_input);

        // 设置数字按钮监听
        int[] numberIds = {
                R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4,
                R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8, R.id.btn_9,
                R.id.btn_dot
        };

        for (int id : numberIds) {
            findViewById(id).setOnClickListener(this);
        }

        // 设置操作符按钮监听
        int[] operatorIds = {
                R.id.btn_add, R.id.btn_subtract, R.id.btn_multiply, R.id.btn_divide,
                R.id.btn_clear, R.id.btn_del, R.id.btn_equal
        };

        for (int id : operatorIds) {
            findViewById(id).setOnClickListener(this);
        }
    }

    /**
     * 检查并请求通知权限（Android 13+）
     */
    private void checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {

                // 请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        PERMISSION_REQUEST_CODE);
            }
        }
    }

    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showToast("通知权限已授予");
            } else {
                showToast("通知权限被拒绝，将无法显示计算结果通知");
            }
        }
    }

    /**
     * 创建通知渠道（Android 8.0+ 必需）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "计算器结果";
            String description = "显示计算器的计算结果";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);

            // 注册通知渠道
            notificationManager.createNotificationChannel(channel);
        }
    }

    /**
     * 检查是否有通知权限
     */
    private boolean hasNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
                    == PackageManager.PERMISSION_GRANTED;
        }
        return true; // Android 13 以下不需要动态权限
    }

    /**
     * 发送通知到状态栏
     */
    private void sendNotification(String expression, String result) {
        // 检查权限
        if (!hasNotificationPermission()) {
            showToast("请授予通知权限以显示计算结果");
            checkNotificationPermission();
            return;
        }

        try {
            // 创建点击通知后打开的Intent
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

            // 构建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_dialog_info)
                    .setContentTitle("计算完成 ✓")
                    .setContentText(expression + " = " + result)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText("计算表达式: " + expression + "\n计算结果: " + result))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setOnlyAlertOnce(true); // 只提醒一次

            // 显示通知
            notificationManager.notify(NOTIFICATION_ID, builder.build());

            // 显示Toast确认通知已发送
            showToast("计算结果已发送到通知栏");

        } catch (Exception e) {
            showToast("发送通知失败: " + e.getMessage());
        }
    }

    /**
     * 发送错误通知
     */
    private void sendErrorNotification(String expression) {
        if (!hasNotificationPermission()) {
            return;
        }

        try {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_dialog_alert)
                    .setContentTitle("计算错误 ⚠️")
                    .setContentText("表达式计算失败")
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText("错误表达式: " + expression + "\n请检查输入格式"))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);

            notificationManager.notify(NOTIFICATION_ID, builder.build());

        } catch (Exception e) {
            showToast("发送错误通知失败");
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_clear) {
            currentInput = "";
            etInput.setText("0");
            clearFlag = false;
        } else if (id == R.id.btn_del) {
            if (currentInput.length() > 0) {
                currentInput = currentInput.substring(0, currentInput.length() - 1);
                etInput.setText(currentInput.isEmpty() ? "0" : currentInput);
            }
        } else if (id == R.id.btn_equal) {
            handleEqualButton();
        } else {
            handleInputButton(v);
        }
    }

    /**
     * 处理等号按钮点击
     */
    private void handleEqualButton() {
        try {
            // 保存原始表达式用于通知
            String originalExpression = currentInput;

            if (originalExpression.trim().isEmpty()) {
                showToast("请输入表达式");
                return;
            }

            double result = eval(currentInput);
            String resultStr = formatResult(result);

            // 更新UI
            etInput.setText(resultStr);
            currentInput = resultStr;
            clearFlag = true;

            // 发送成功通知
            sendNotification(originalExpression, resultStr);

        } catch (Exception e) {
            etInput.setText("错误");
            currentInput = "";
            clearFlag = true;

            // 发送错误通知
            sendErrorNotification(currentInput);
        }
    }

    /**
     * 处理输入按钮点击
     */
    private void handleInputButton(View v) {
        if (clearFlag) {
            currentInput = "";
            clearFlag = false;
        }

        String buttonText = ((Button) v).getText().toString();

        // 简单的输入验证
        if (isOperator(buttonText) && !currentInput.isEmpty()) {
            currentInput += " " + buttonText + " ";
        } else {
            currentInput += buttonText;
        }

        etInput.setText(currentInput);
    }

    /**
     * 显示Toast消息
     */
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 格式化结果，去除不必要的 .0
     */
    private String formatResult(double result) {
        if (result == (long) result) {
            return String.format("%d", (long) result);
        } else {
            return String.format("%s", result);
        }
    }

    /**
     * 计算表达式的方法
     */
    private double eval(String expression) {
        try {
            return new ExpressionEvaluator(expression).parse();
        } catch (Exception e) {
            throw new RuntimeException("计算错误");
        }
    }

    /**
     * 表达式计算器内部类
     */
    private static class ExpressionEvaluator {
        private final String expression;
        private int pos = -1;
        private int ch;

        public ExpressionEvaluator(String expression) {
            this.expression = expression;
        }

        private void nextChar() {
            ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
        }

        private boolean eat(int charToEat) {
            while (ch == ' ') nextChar();
            if (ch == charToEat) {
                nextChar();
                return true;
            }
            return false;
        }

        public double parse() {
            nextChar();
            double x = parseExpression();
            if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char) ch);
            return x;
        }

        private double parseExpression() {
            double x = parseTerm();
            for (; ; ) {
                if (eat('+')) x += parseTerm();
                else if (eat('-')) x -= parseTerm();
                else return x;
            }
        }

        private double parseTerm() {
            double x = parseFactor();
            for (; ; ) {
                if (eat('×')) x *= parseFactor();
                else if (eat('*')) x *= parseFactor();
                else if (eat('÷')) x /= parseFactor();
                else if (eat('/')) x /= parseFactor();
                else return x;
            }
        }

        private double parseFactor() {
            if (eat('+')) return parseFactor();
            if (eat('-')) return -parseFactor();

            double x;
            int startPos = this.pos;
            if (eat('(')) {
                x = parseExpression();
                eat(')');
            } else if ((ch >= '0' && ch <= '9') || ch == '.') {
                while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                x = Double.parseDouble(expression.substring(startPos, this.pos));
            } else {
                throw new RuntimeException("Unexpected: " + (char) ch);
            }

            return x;
        }
    }

    /**
     * 判断是否为运算符
     */
    private boolean isOperator(String text) {
        return text.equals("+") || text.equals("-") || text.equals("×") || text.equals("÷");
    }
}